package com.ldzysoft.myweather.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bumptech.glide.Glide;
import com.ldzysoft.myweather.gson.Forecast;
import com.ldzysoft.myweather.gson.Weather;
import com.ldzysoft.myweather.service.AutoUpdateService;
import com.ldzysoft.myweather.utils.HttpUtil;
import com.ldzysoft.myweather.utils.JsonUtil;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import com.ldzysoft.myweather.R;
import com.tbruyelle.rxpermissions2.RxPermissions;

public class WeatherActivity extends AppCompatActivity {

    private static final String TAG = "WeatherActivity";

    public SwipeRefreshLayout swipeRefresh;
    public DrawerLayout drawerLayout;
    private ScrollView weatherLayout;
    private LinearLayout forecastLayout;

    private TextView titleCity, titleUpdateTime;
    private TextView degree, weatherInfo;
    private TextView aqi, pm25, comfort, carWash, sport;
    private ImageView bingImg;
    private Button nav;

    private String weatherId, weatherString;
    private Weather weather;
    private SharedPreferences prefs;
    private RxPermissions rxPermissions;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        setContentView(R.layout.activity_weather);

        rxPermissions = new RxPermissions(this);

        // 初始化控件
        initView();

        // 监听导航按钮的点击事件
        nav.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawerLayout.openDrawer(GravityCompat.START);
            }
        });

        prefs = PreferenceManager.getDefaultSharedPreferences(this);
        weatherString = prefs.getString("weather", null);
        if (weatherString != null) {
            // 有缓存，直接展示天气信息
            weather = JsonUtil.handleWeatherData(weatherString);
            weatherId = weather.basic.weatherId;
            showWeatherInfo(weather);
        } else {
            // 无缓存，请求服务器
            weatherId = getIntent().getStringExtra("weather_id");
            weatherLayout.setVisibility(View.INVISIBLE);
            requestWeather(weatherId);
        }

        // 下拉刷新控件的设置和下拉事件监听
        swipeRefresh.setColorSchemeResources(R.color.colorPrimary);
        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // 从SharedPreferences中取出当前选中城市的信息
                weatherString = prefs.getString("weather", null);
                if (weatherString != null) {
                    weather = JsonUtil.handleWeatherData(weatherString);
                    weatherId = weather.basic.weatherId;
                    requestWeather(weatherId);
                }
            }
        });

        // 获取SharedPreferences中的必应每日一图
        String bingImgString = prefs.getString("bing_img", null);
        if (bingImgString != null) {
            Glide.with(this).load(bingImgString).into(bingImg);
        } else {
            loadBingImg();
        }
    }

    /*
    * 初始化控件
    * */
    private void initView() {
        drawerLayout = findViewById(R.id.drawer_layout);
        swipeRefresh = findViewById(R.id.swipe_refresh);
        weatherLayout = findViewById(R.id.weather_layout);
        forecastLayout = findViewById(R.id.forecast_layout);

        titleCity = findViewById(R.id.title_city);
        titleUpdateTime = findViewById(R.id.title_update_time);

        degree = findViewById(R.id.degree);
        weatherInfo = findViewById(R.id.weather_info);

        aqi = findViewById(R.id.aqi);
        pm25 = findViewById(R.id.pm25);
        comfort = findViewById(R.id.comfort);
        carWash = findViewById(R.id.car_wash);
        sport = findViewById(R.id.sport);

        nav = findViewById(R.id.nav);
        bingImg = findViewById(R.id.bing_img);
    }

    /*
     * 请求天气信息
     * */
    public void requestWeather(String weatherId) {
        String weatherUrl = "http://guolin.tech/api/weather?cityid="
                + weatherId + "&key=bc0418b57b2d4918819d3974ac1285d9";
        Log.e(TAG, weatherUrl);

        HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
                        swipeRefresh.setRefreshing(false);  // 停止刷新
                    }
                });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String weatherData = response.body().string();
                Weather weather = JsonUtil.handleWeatherData(weatherData);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (weather != null && "ok".equals(weather.status)) {
                            // 请求成功后，将当前城市的天气信息写入SharedPreferences中
                            SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
                            editor.putString("weather", weatherData);
                            editor.apply();
                            showWeatherInfo(weather);
                        } else {
                            Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
                        }
                        swipeRefresh.setRefreshing(false);
                    }
                });
            }
        });

        loadBingImg();
    }

    /*
     * 显示天气信息
     * */
    private void showWeatherInfo(Weather weather) {
        String cityName = weather.basic.cityName;
        titleCity.setText(cityName);

        String updateTime = weather.basic.update.updateTime.split(" ")[1];
        titleUpdateTime.setText(updateTime);

        String degreeString = weather.now.temperature + "°C";
        degree.setText(degreeString);

        String weatherInfoString = weather.now.more.info;
        weatherInfo.setText(weatherInfoString);

        forecastLayout.removeAllViews();
        for (Forecast forecast : weather.forecastList) {
            View view = LayoutInflater.from(this).inflate(R.layout.weather_forecast_item, forecastLayout, false);
            TextView date, info, max, min;

            date = view.findViewById(R.id.date);
            date.setText(forecast.date);

            info = view.findViewById(R.id.info);
            info.setText(forecast.more.info);

            max = view.findViewById(R.id.max);
            max.setText(forecast.temperature.max);

            min = view.findViewById(R.id.min);
            min.setText(forecast.temperature.min);

            forecastLayout.addView(view);
        }

        if (weather.aqi != null) {
            aqi.setText(weather.aqi.city.aqi);
            pm25.setText(weather.aqi.city.pm25);
        }

        String comfortString = "舒适度：" + weather.suggestion.comfort.info;
        comfort.setText(comfortString);

        String carWashString = "洗车指数：" + weather.suggestion.carWash.info;
        carWash.setText(carWashString);

        String sportString = "运动建议：" + weather.suggestion.sport.info;
        sport.setText(sportString);

        weatherLayout.setVisibility(View.VISIBLE);

        // 启动自动更新天气的Service
        Intent intent = new Intent(WeatherActivity.this, AutoUpdateService.class);
        startService(intent);
    }

    /*
     * 加载必应每日一图
     * */
    private void loadBingImg() {
        String bingImgUrl = "http://guolin.tech/api/bing_pic";
        Log.e(TAG, bingImgUrl);

        HttpUtil.sendOkHttpRequest(bingImgUrl, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String bingImgString = response.body().string();  // http://cn.bing.com/th?id=OHR.Rhododendron_ROW6096476187_1920x1080.jpg&rf=LaDigue_1920x1081920x1080.jpg
                SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
                editor.putString("bing_img", bingImgString);
                editor.apply();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Glide.with(WeatherActivity.this).load(bingImgString).into(bingImg);
                    }
                });
            }
        });
    }
}
